package com.snailvr.tv.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.snail.readyvr.R;
import com.snail.readyvr.event.LoginEvent;
import com.snail.readyvr.util.EventBus;
import com.snail.readyvr.util.StartActivityUtils;
import com.snail.readyvr.util.ToastUtils;
import com.snailvr.tv.Definition;
import com.snailvr.tv.contract.RoomContact;
import com.snailvr.tv.event.RoomChangeEvent;
import com.snailvr.tv.network.entity.JXListResponBean;
import com.snailvr.tv.network.entity.RoomInfoBean;
import com.snailvr.tv.network.entity.RoomListResponBean;
import com.snailvr.tv.presenter.RoomPresenter;
import com.snailvr.tv.ui.adapter.GridSpacingItemDecoration;
import com.snailvr.tv.ui.adapter.JXDownloadAdapter;
import com.snailvr.tv.ui.adapter.RoomAdapter;
import com.snailvr.tv.ui.base.CheckPermissionsActivity;
import com.snailvr.tv.network.entity.JXListResponBean.DataBean.ListBean;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import party.loveit.download.core.DLListenerMgr;
import party.loveit.download.core.DLManager;
import party.loveit.download.listener.IDListener;

import static com.snailvr.tv.Definition.CHANNEL_ID_NAME;

;

/**
 * Created by Administrator on 2016/9/30.
 */
public class RoomsActivity extends CheckPermissionsActivity implements RoomContact.IRoomView, IDListener{

    private List<RoomListResponBean.DataBean.ListBean> mRoomList;
    private List<ListBean> mJXList;
    private RoomAdapter mRoomAdapter;
    private JXDownloadAdapter mJXDownloadAdapter;
    private RoomContact.IRoomPresenter mRoomPresenter;
    private int page;
    private int page_size;
    private int channel_id;

    private RecyclerView mRecyclerViewRooms;
    private RecyclerView mRecyclerViewDownloads;
    private String[] mTitleList;//页卡标题集合
    private List<View> mViewList = new ArrayList<>();//页卡视图集合

    private static int TAB_MARGIN_DIP = 60;

    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;

    @BindView(R.id.view_pager)
    ViewPager mViewPager;

    @BindView(R.id.buffering_view)
    RelativeLayout mBufferingView;

    @BindView(R.id.txt_view_1)
    TextView mTextView1;

    @BindView(R.id.txt_view_2)
    TextView mTextView2;

    @Override
    protected void initVariables() {
        mRoomList = new ArrayList<>();
        mRoomPresenter = new RoomPresenter();
        mRoomPresenter.registerView(this);
        mRoomAdapter = new RoomAdapter(this, mRoomList, new RoomAdapter.onRoomChangeListener() {
            @Override
            public void onRoomChange(int room_id) {
                mRoomPresenter.loadRoomInfo(room_id);
            }
        });
        mJXList = new ArrayList<>();
        mJXDownloadAdapter = new JXDownloadAdapter(this,mJXList);
        page = 0;
        page_size = 20;
        channel_id = getIntent().getIntExtra(CHANNEL_ID_NAME, 0);

        mTitleList = this.getResources().getStringArray(R.array.tab_title);

        DLListenerMgr.getInstance().register(this);

    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.room_list);
        ButterKnife.bind(this);

        mBufferingView.setVisibility(View.VISIBLE);

        mTextView1.setText(mTitleList[0]);
        mTextView1.setTextColor(getResources().getColor(R.color.player_title_color));
        mTextView2.setText(mTitleList[1]);

        GridLayoutManager manager = new GridLayoutManager(this, Definition.COLUMU_NUM);
        mRecyclerViewRooms = new RecyclerView(this);

        mRecyclerViewRooms.setLayoutManager(manager);
        mRecyclerViewRooms.setAdapter(mRoomAdapter);
        mRecyclerViewRooms.addItemDecoration(new GridSpacingItemDecoration(Definition.COLUMU_NUM,Definition.COLUMU_SPACE));

        manager = new GridLayoutManager(this, Definition.COLUMU_NUM);
        mRecyclerViewDownloads = new RecyclerView(this);

        mRecyclerViewDownloads.setLayoutManager(manager);
        mRecyclerViewDownloads.setAdapter(mJXDownloadAdapter);
        mRecyclerViewDownloads.addItemDecoration(new GridSpacingItemDecoration(Definition.COLUMU_NUM,Definition.COLUMU_SPACE));

        mViewList.add(mRecyclerViewRooms);
        mViewList.add(mRecyclerViewDownloads);

        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(mViewList);
        mViewPager.setAdapter(myPagerAdapter);

        mTabLayout.setupWithViewPager(mViewPager);

        setIndicator(this,mTabLayout,TAB_MARGIN_DIP,TAB_MARGIN_DIP);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    mTextView1.setTextColor(getResources().getColor(R.color.player_title_color));
                    mTextView2.setTextColor(getResources().getColor(R.color.player_title_color_trans_50));
                } else {
                    mTextView1.setTextColor(getResources().getColor(R.color.player_title_color_trans_50));
                    mTextView2.setTextColor(getResources().getColor(R.color.player_title_color));
                }


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void loadData() {
        Log.i(TAG,"channel_id:" + channel_id);
        mBufferingView.setVisibility(View.VISIBLE);
        mRoomPresenter.loadRoomList(channel_id,0,page_size,false,false);
        mRoomPresenter.loadJXList(page,page_size);
    }

    @OnClick(R.id.id_layout_close)
    public void onClose() {
        this.finish();
    }

    @Override
    public void showRoomInfo(RoomInfoBean _bean) {
        Log.i(TAG,"showRoomInfo");
        if (!_bean.isCharge()) {
            EventBus.getDefault().post(new RoomChangeEvent(_bean));
            this.finish();
        } else {
            // show pay dialog
            ToastUtils.show(this,"Paypal is not already, pls wait!");
        }
    }

    @Override
    public void showRoomList(RoomListResponBean _bean) {
        mBufferingView.setVisibility(View.GONE);
        this.mRoomList.addAll(_bean.getData().getList());
        Log.i(TAG,"mRoomList num:" + mRoomList.size());
        mRoomAdapter.notifyDataSetChanged();
    }

    @Override
    public void showJXList(JXListResponBean.DataBean _bean) {
        this.mJXList.addAll(_bean.getList());
        Iterator<ListBean> mIterator;
        for (mIterator=mJXList.iterator();mIterator.hasNext();) {
            ListBean bean = mIterator.next();
            if(DLManager.getInstance().getDLInfo(bean.getDownloadurl()) == null) {
                bean.setDownloadStatus(ListBean.DownloadStatus.UnDownLoad);
            } else {
                bean.setDownloadStatus(ListBean.DownloadStatus.Downloaded);
            }
        }
        Log.i(TAG,"mJXList num:" + mJXList.size());
        mJXDownloadAdapter.notifyDataSetChanged();

    }

    @Override
    public void showLoadFailureMsg(int code, String errorMsg) {
        ToastUtils.show(this,errorMsg);
        if (code == 001013) {
            StartActivityUtils.startLoginActivity(this,null, LoginEvent.FROM_PLAYER);
        }

    }

    @Override
    protected void hasGetAllPermissions() {

    }
    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0,R.anim.slide_bottom_out);
        mRoomPresenter.unregisterView();
    }

    //ViewPager适配器
    class MyPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount() {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));//删除页卡
        }
    }

    public static void setIndicator(Context context, TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout ll_tab = null;
        try {
            ll_tab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) (getDisplayMetrics(context).density * leftDip);
        int right = (int) (getDisplayMetrics(context).density * rightDip);

        for (int i = 0; i < ll_tab.getChildCount(); i++) {
            View child = ll_tab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.setMarginStart(left);
            params.setMarginEnd(right);
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric;
    }

    @Override
    public void onPrepare(String baseUrl) {

    }

    @Override
    public void onStart(String fileName, String baseUrl, long fileLength) {
        Iterator<ListBean> mIterator;
        for (mIterator=mJXList.iterator();mIterator.hasNext();) {
            ListBean bean = mIterator.next();
            if(bean.getDownloadurl().equals(baseUrl)) {
                bean.setDownloadStatus(ListBean.DownloadStatus.Downloading);
            }
        }

        mJXDownloadAdapter.notifyDataSetChanged();
    }

    @Override
    public void onProgress(String baseUrl, String speed, long progress) {
        Iterator<ListBean> mIterator;
        for (mIterator=mJXList.iterator();mIterator.hasNext();) {
            ListBean bean = mIterator.next();
            if(bean.getDownloadurl().equals(baseUrl)) {
                bean.setProgress(progress);
            }
        }
        mJXDownloadAdapter.notifyDataSetChanged();


    }

    @Override
    public void onStop(String baseUrl, long progress) {


    }

    @Override
    public void onFinish(String baseUrl, File file) {
        Iterator<ListBean> mIterator;
        for (mIterator=mJXList.iterator();mIterator.hasNext();) {
            ListBean bean = mIterator.next();
            if(bean.getDownloadurl().equals(baseUrl)) {
                bean.setDownloadStatus(ListBean.DownloadStatus.Downloaded);
            }
        }
        mJXDownloadAdapter.notifyDataSetChanged();

    }

    @Override
    public void onError(String baseUrl, int status, String error) {
        Iterator<ListBean> mIterator;
        for (mIterator=mJXList.iterator();mIterator.hasNext();) {
            ListBean bean = mIterator.next();
            if(bean.getDownloadurl().equals(baseUrl)) {
                bean.setDownloadStatus(ListBean.DownloadStatus.UnDownLoad);
            }
        }

    }
}
